package com.sky.task;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.orderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * ClassName: OrderTask
 * Package: com.sky.task
 * Description:对超时未支付的订单和派送中的订单进行定时操作处理
 *
 * @Author: 葛龙
 * @Create 2025/3/6 15:40
 * @Version 1.0
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private orderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ?") //每分钟执行一次
    public void processTimeoutOrder() {
        log.info("超时订单处理:{}", new Date());
        //调用orderMapper将超时的订单查询出来 参数：订单状态、订单时间
        //select * form orders where status = #{status} and order_time < (当前时间 - 15); 返回的是一个集合List
        final LocalDateTime time = LocalDateTime.now().plusMinutes(-15); // 当前时间-15分钟
        List<Orders> list = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点执行一次
    public void processDeliveryOrder() {
        log.info("处理派送中订单：{}", new Date());
        // select * from orders where status = 4 and order_time < 当前时间-1小时 正好是前一天的结束
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }

}
